package com.example.office365wopi.rest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class IdUrlMap {
    //演示使用
    private static final Map<String, FileItem> ID_URL_MAP = new ConcurrentHashMap<>();
    private static final Map<String, FileItem> URL_ID_MAP = new ConcurrentHashMap<>();



    @Value("${officeURL}")
    private String officeURL;

    public FileItem getUrl(String fileId) {
        FileItem fileItem = ID_URL_MAP.get(fileId);
        if (fileItem != null) {
            return fileItem;
        }
        return null;
    }

    public FileItem getIdAndPut(String url) {
        FileItem fileItem = URL_ID_MAP.get(url);
        if (fileItem == null) {
            String fileId = generateMessageDigest(url);;
            String fileName = getFileName(url);
            if (fileName != null) {
                fileName= fileName.replace('+','_');
            }
            fileItem = new FileItem(fileId, url, fileName);

            ID_URL_MAP.put(fileId, fileItem);
            URL_ID_MAP.put(url, fileItem);
        }
        fileItem.setOfficeURL(officeURL);
        log.info("ID_URL_MAP={}", ID_URL_MAP);
        log.info("URL_ID_MAP={}", URL_ID_MAP);
        return fileItem;
    }

    public static Map<String, String> splitQuery(URI uri) throws URISyntaxException, UnsupportedEncodingException {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        String query = uri.getQuery();
        if (query == null) {
            return queryPairs;
        }
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            if (idx > 0) {
                String key = pair.substring(0, idx);
                if (pair.length() > key.length() + 1) {
                    String value = pair.substring(idx + 1);
                    queryPairs.put(key, URLDecoder.decode(value));
                }
            }
        }
        return queryPairs;
    }

    private String getFileName(String url) {
        try {
            URI uri = new URI(url);
            Map<String, String> param = splitQuery(uri);
            String title = param.get("title");
            if (title != null) {
                return title;
            } else {
                String path = uri.getPath();
                int index = path.lastIndexOf("/");
                if (index >=0) {
                    return path.substring(index + 1);
                }
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    public  static  String   generateMessageDigest(String message) {

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(message.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

          return hexString.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
